﻿'
' Created by SharpDevelop.
' User: mike_sh
' Date: 11/14/2009
' Time: 12:00 AM
'
' To change this template use Tools | Options | Coding | Edit Standard Headers.
'
Imports System.Windows.Controls
Imports System.Management.Automation


Public Module PWBUIHandling
    Private Menus As New Dictionary(Of String, Controls.ContextMenu)
    Private menuVersion As Integer = 0
    Public Trees As New Dictionary(Of String, TreeView)
    Private blnScrollPending As Boolean = False

    Public Class UIAction
        Public ActionDateTime As Date
        Public UIActionID As Integer
        Public ActionType As String
        Public Message As String
        Public Tag As Object
        Public ForegroundColor As Color
        Public BackgroundColor As Color
        Public strings As New Collections.Specialized.StringDictionary
        Public objects As New Dictionary(Of String, Object)
        Public Sub New(ByVal strActionType As String, Optional ByVal strMessage As String = "")
            ActionType = strActionType
            Message = strMessage
        End Sub
    End Class
	Public UIEvents As New List(Of UIAction)

    Public Sub ProcessEvents()
        blnScrollPending = False
        While UIEvents.Count > 0
            ProcessEvent(UIEvents(0))
            UIEvents.RemoveAt(0)
        End While
        If blnScrollPending Then
            WorkBench.OutputBox.ScrollToEnd()
        End If
    End Sub
    Private Sub ProcessEvent(ByVal act As UIAction)
        Select Case act.ActionType
            Case "Write"
                WorkBench.OutputBox.AppendText(act.Message)
                blnScrollPending = True
            Case "ClearHost"
                WorkBench.OutputBox.Clear()
            Case "NewTree"
                NewTree(act)
            Case "NewTreeNode"
                Dim t As TreeView
                Dim _node As New TreeViewItem
                Dim strTreeName As String = act.strings("TreeName")
                Dim strParentName As String = act.strings("ParentName")
                Dim oParent As PSObject = CType(act.objects("ParentObject"), PSObject)
                Dim oNode As PSObject = CType(act.objects("NodeObject"), PSObject)
                _node.Header = act.strings("NodeName")
                _node.Tag = oNode
                Try
                    t = Trees(strTreeName)
                Catch ex As Exception
                    NewTree(New UIAction("NewTree", strTreeName))
                    t = Trees(strTreeName)
                End Try
                Dim _parent As TreeViewItem = FindNodeInTree(strParentName, t.Items, oParent)
                If _parent Is Nothing Then
                    If strParentName <> "" Then
                        _parent = New TreeViewItem
                        _parent.Header = strParentName
                        t.Items.Add(_parent)
                        _parent.Items.Add(_node)
                    Else
                        t.Items.Add(_node)
                    End If
                Else
                    _parent.Items.Add(_node)
                End If
            Case "ClearTree"
                Dim t As TreeView
                Dim strTreeName As String = act.Message
                Try

                    t = Trees(strTreeName)
                    t.Items.Clear()
                Catch ex As Exception

                End Try
            Case "RemoveTree"
                Dim t As TreeView
                Dim strTreeName As String = act.Message
                Try

                    Dim oLeftPanel As AvalonDock.DocumentPane
                    t = Trees(strTreeName)
                    Trees.Remove(strTreeName)
                    Dim d As AvalonDock.DockableContent
                    d = CType(t.Parent, AvalonDock.DockableContent)
                    oLeftPanel = CType(WorkBench.LeftRightPanel.Children(0), AvalonDock.DocumentPane)
                    oLeftPanel.Items.Remove(d)
                    If oLeftPanel.Items.Count = 0 Then
                        WorkBench.LeftRightPanel.Children.Remove(oLeftPanel)
                        
                    End If
                Catch ex As Exception

                End Try
            Case "NewTypeMenuItem"
                Dim _typename As String = act.Message
                Dim _action As Object = act.objects("Action")
                Dim _name As String = act.strings("Name").Replace("_", " ")
                Dim cntTypeMenu As ContextMenu
                If Menus.ContainsKey(_typename) Then
                    cntTypeMenu = Menus(_typename)
                Else
                    cntTypeMenu = New ContextMenu
                    Menus(_typename) = cntTypeMenu
                End If
                Dim mi As New MenuItem
                mi.Header = _name
                If TypeOf (_action) Is String Then
                    mi.Tag = _action
                ElseIf TypeOf (_action) Is Collections.Hashtable Then
                    Dim d As Hashtable = CType(_action, Hashtable)
                    Dim submenu As MenuItem
                    For Each k As String In d.Keys
                        submenu = New MenuItem
                        submenu.Header = k.Replace("_", " ")
                        submenu.Tag = d(k)
                        mi.Items.Add(submenu)
                    Next

                End If
                cntTypeMenu.Items.Add(mi)
                menuVersion += 1
            Case Else

        End Select
    End Sub
    Function FindNodeInTree(ByVal nodename As String, ByVal nodes As ItemCollection, ByVal objTag As Object) As TreeViewItem
        Dim rtn As TreeViewItem = Nothing

        For Each node As TreeViewItem In nodes
            If Equals(node.Tag, objTag) And objTag IsNot Nothing Then
                Return node
            ElseIf (objTag Is Nothing) AndAlso (CType(node.Header, String) = nodename) Then
                Return node
            Else
                rtn = FindNodeInTree(nodename, node.Items, objTag)
                If rtn IsNot Nothing Then
                    Return rtn
                End If
            End If
        Next
        Return Nothing
    End Function

    Sub NewTree(ByVal act As UIAction)
        Dim oLeftPanel As AvalonDock.DocumentPane
        Dim t As New TreeView
        AddHandler t.MouseDoubleClick, AddressOf TreeView1_MouseDoubleClick
        AddHandler t.PreviewMouseRightButtonDown, AddressOf TreeView_MouseRightClick
        If Trees.ContainsKey(act.Message) Then Return
        Trees.Add(act.Message, t)
        If WorkBench.LeftRightPanel.Children.Count = 1 Then
            oLeftPanel = New AvalonDock.DocumentPane
            WorkBench.LeftRightPanel.Children.Insert(0, oLeftPanel)
        Else
            oLeftPanel = CType(WorkBench.LeftRightPanel.Children(0), AvalonDock.DocumentPane)
        End If
        Dim d As New AvalonDock.DockableContent
        d.Content = t
        d.Title = act.Message
        t.HorizontalAlignment = HorizontalAlignment.Stretch
        t.VerticalAlignment = VerticalAlignment.Stretch
        oLeftPanel.Items.Add(d)
        AddHandler d.IsVisibleChanged, AddressOf DockableContent_IsVisibleChanged
        oLeftPanel.SelectedItem = d

    End Sub

    Public Sub DockableContent_IsVisibleChanged(ByVal sender As System.Object, ByVal e As System.Windows.DependencyPropertyChangedEventArgs)
        Dim d As AvalonDock.DockableContent = CType(sender, AvalonDock.DockableContent)
        If CBool(e.NewValue) = False Then
            If TypeOf d.Content Is TreeView Then
                Trees.Remove(d.Title)
            End If
        End If
        'If WorkBench.Instance.IsVisible AndAlso CType(WorkBench.LeftRightPanel.Children(WorkBench.LeftRightPanel.Children.Count - 1), AvalonDock.ResizingPanel).Children.Count = 0 Then
        '    WorkBench.Instance.btnNew_Click(Nothing, Nothing)
        'End If
    End Sub
    Private Sub TreeView1_MouseDoubleClick(ByVal sender As System.Object, ByVal e As System.Windows.Input.MouseButtonEventArgs)
        Dim tvi As TreeViewItem
        tvi = CType(CType(sender, TreeView).SelectedItem, TreeViewItem)

        InvokeString("""" & tvi.Tag.ToString & """")
    End Sub
    Private Sub TreeView_MouseRightClick(ByVal sender As System.Object, ByVal e As System.Windows.Input.MouseButtonEventArgs)
        Dim tvi As TreeViewItem = CType(VisualUpwardSearch(Of TreeViewItem)(CType(e.OriginalSource, DependencyObject)), TreeViewItem)

        If tvi IsNot Nothing Then
            tvi.IsSelected = True
            e.Handled = True
            Dim cm As ContextMenu = Nothing

            If tvi.Tag IsNot Nothing Then
                Dim pso As New PSObject(tvi.Tag)
                cm = New ContextMenu
                For Each t As String In pso.TypeNames
                    If Menus.ContainsKey(t) Then
                        For Each itm As MenuItem In CType(Menus(t), ContextMenu).Items
                            Dim itm2 As New MenuItem
                            itm2.Header = itm.Header
                            If itm.Items.Count > 0 Then
                                Dim sub2 As MenuItem
                                For Each subitem As MenuItem In itm.Items
                                    sub2 = New MenuItem
                                    sub2.Header = subitem.Header
                                    sub2.Tag = subitem.Tag
                                    itm2.Items.Add(sub2)
                                Next
                            Else
                                itm2.Header = itm.Header
                                itm2.Tag = itm.Tag

                            End If
                            AddHandler itm2.Click, AddressOf MenuItemClicked
                            cm.Items.Add(itm2)
                        Next
                    End If
                Next
                If cm IsNot Nothing Then
                    cm.Tag = pso
                    tvi.ContextMenu = cm
                End If
            End If

        End If

    End Sub

    Function VisualUpwardSearch(Of T)(ByVal source As DependencyObject) As DependencyObject
        While (source IsNot Nothing And Not TypeOf source Is T)
            source = VisualTreeHelper.GetParent(source)
        End While
        Return source
    End Function

    Private Sub MenuItemClicked(ByVal sender As Object, ByVal e As RoutedEventArgs)
        Dim action As String
        Dim pso As PSObject
        Dim mnu As MenuItem = CType(e.OriginalSource, MenuItem)
        Dim parent As ContextMenu
        Dim varname As String = IO.Path.GetFileNameWithoutExtension(IO.Path.GetTempFileName)
        action = CStr(mnu.Tag)
        parent = CType(VisualUpwardSearch(Of ContextMenu)(CType(sender, DependencyObject)), ContextMenu)
        pso = CType(parent.Tag, PSObject)
        CreateVariable(varname, pso)
        InvokeString(action.Replace("*OBJECT*", "${" & varname & "}"))

    End Sub
End Module
